<!--
 * @Description: 单据编码规则
 * @Author: 
 * @Date: 2020-06-29 11:18:28
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-08-09 15:24:15
-->
<template>
  <div class="pages_content table CodingRules">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main style="display: flex;">
        <div v-loading='treeLoading' class="main_left scroll" style="width: 200px;padding: 20px;">
          <div style="padding-right:10px;">
            <el-tree :data="orangeoptions" :props="defaultProps" :expand-on-click-node="false" class="tree-line" :indent="0" @node-click="setTree">
              <span slot-scope="{ node, data }" class="custom-tree-node">
                <div v-if="data.url" style="display: inline-block;width:17px;height:26px;padding:8px 3px 0 0">
                  <img style="width:14px;height:14px" :src="'/file/'+data.url" />
                </div>
                <span style="padding-right:10px;">{{ node.label }}</span>
              </span>
            </el-tree>
          </div>
        </div>
        <div class="main_right">
          <div class="header_right" @click="showCardNav = !showCardNav">
            <div class="title">搜索</div>
            <div>
              <div :class="{ 'arrowTransform': !showCardNav, 'arrowTransformReturn': showCardNav}">
                <i style="margin-right: 5px" class="el-icon-arrow-down"></i>
              </div>
            </div>
          </div>
          <div v-show="showCardNav" class="hr"></div>
          <el-collapse-transition>
            <div v-show="showCardNav">
              <div class="search">
                <el-form ref="form" :inline="true" :model="form">
                  <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入" @keyup.enter.native="initData()"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button icon="el-icon-search" size="medium" class="bottom_all" @click="initData()">查 询</el-button>
                    <el-button size="medium" class="bottom_all_two" @click="form.organizationId='',resetData()">重 置</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-collapse-transition>
          <div class="hr"></div>
          <div class="card">
            <div class="card_nav">
              <div>
                <el-button v-if="userInfo.createChindAccount==1&&ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0;" @click="add()">
                  <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
                  添加
                </el-button>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='RIYONG'))!==-1" size="small" class="bottom_three" @click="updateType(1)">
                  <i class="icon iconfont iconicon_button_startuse" style="font-size: 12px;"></i>
                  启用
                </el-button>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='JINYONG'))!==-1" size="small" class="bottom_four" @click="updateType(2)">
                  <i class="icon iconfont iconicon_button_disable1" style="font-size: 12px;"></i>
                  禁用
                </el-button>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='SHANCHU'))!==-1" size="small" class="bottom_two" @click="updateType(3)">
                  <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
                  删除
                </el-button>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='DAORU'))!==-1" size="small" class="botton_five" @click="exportDialog = true">导入用户</el-button>
                <el-button size="small" class="botton_five" @click="resetPassword">重置密码</el-button>
              </div>
              <div>
                <el-link v-if="ButtonList.findIndex(res=>(res.buttonValue=='BAOCUNPXH'))!==-1" :underline="false" @click="updateSortNum()">
                  <span class="el-icon--left">
                    <i class="iconfont iconicon_button_sort1"></i>
                  </span>
                  保存排序号
                </el-link>
                <el-dropdown :hide-on-click="false" trigger="click" style="margin: 0 20px;">
                  <el-link :underline="false">
                    <span class="el-icon--left">
                      <i class="iconfont iconicon_button_filtrate"></i>
                    </span>
                    筛选
                  </el-link>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(item, index) in tableColumns" :key="index">
                      <el-checkbox v-model="item.status">{{ item.label }}</el-checkbox>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-link v-if="ButtonList.findIndex(res=>(res.buttonValue=='DAOCHU'))!==-1" :underline="false" @click="$Download(DownloadURL, form);">
                  <span class="el-icon--left">
                    <i class="iconfont iconicon_button_export1"></i>
                  </span>
                  导出
                </el-link>
              </div>
            </div>
            <div class="card_info" :style="style">
              <el-table v-loading='tableLoading' :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%;overflow: auto;" :data="tableData" tooltip-effect="dark" @selection-change="handleSelectionChange">
                <el-table-column align="center" type="selection"></el-table-column>
                <template v-for="(item, index) in tableColumns">
                  <el-table-column v-if="item.status" :key="index" :label="item.label" align="center" :min-width="item.width" :fixed=" item.label =='操作'?'right':false">
                    <template slot-scope="scope">
                      <span v-if="item.label == '性别'">{{ scope.row.sex == 0 ? '未知' : scope.row.sex == 1 ? '男' : '女' }}</span>
                      <span v-else-if="item.label == '登录方式'">{{ scope.row.loginType == 1 ? '用户名' : '手机号' }}</span>
                      <span v-else-if="item.label == '是否支持创建子账号'">{{ scope.row.createChindAccount == 0 ? '不支持' : '支持' }}</span>
                      <div v-else-if="item.label == '状态'">
                        <span v-if="scope.row.enable == 0 " style="color:#969799;">禁用</span>
                        <span v-if="scope.row.enable == 1 " style="color:#00A754;">启用</span>
                      </div>
                      <div v-else-if="item.label == '排序号'">
                        <el-input v-model="scope.row.sortNum"></el-input>
                      </div>
                      <div v-else-if="item.label == '操作'">
                        <el-button class="bottom_one" size="mini" @click="update(scope.row)">
                          <i class="icon iconfont iconicon_button_modification" style="font-size: 12px;"></i>
                          修改
                        </el-button>
                      </div>
                      <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
            <div class="card_bottom">
              <div class="card_bottom_left">
                <div class="top_page_totle">总共{{ total }}条</div>
                <el-pagination :page-size="pageSize" :page-sizes="[10, 20, 30, 40,50,100,200,500,1000]" layout="prev,pager,sizes,next,jumper" :total="total" :current-page.sync="page" @current-change="initData()" @size-change="sizeChange"></el-pagination>
              </div>
              <div>
                <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="initData()">刷新</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="dialogVisible" width="800px" :close-on-click-modal="false" :before-close="resefrom">
      <span slot="title" class="dialog-title">{{ dialogtitle }}</span>
      <el-form ref="dialogForm" :model="dialogForm" :rules="rules" :inline="true" label-width="150px">
        <el-form-item prop="name">
          <template slot="label">
            <span style="color:#FF0000">名称</span>
          </template>
          <el-input v-model="dialogForm.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item prop="organizationId">
          <template slot="label">
            <span style="color:#FF0000">所属组织</span>
          </template>
          <span style="cursor:pointer;" @click.stop="showVisible">{{dialogForm.organizationIdarr}}</span>
        </el-form-item>
        <el-form-item prop="stationId">
          <template slot="label">
            <span>岗位</span>
          </template>
          <el-select v-model="dialogForm.stationId" placeholder="请选择">
            <el-option v-for="(item, index) in stationoptions" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phoneNum">
          <el-input v-model="dialogForm.phoneNum" maxlength="11" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="登录账号" prop="loginAccount">
          <el-input v-model="dialogForm.loginAccount" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="登录方式" prop="loginType">
          <el-select v-model="dialogForm.loginType" multiple placeholder="请选择">
            <el-option label="用户名" :value="1"></el-option>
            <el-option label="手机号" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序号">
          <el-input v-model="dialogForm.sortNum" type="Number" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="enable">
          <el-radio-group v-model="dialogForm.enable">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="dialogVisible = false">取 消</el-button>
        <el-button class="bottom_all" @click="sureSubmit()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog v-dialogDrag :visible.sync="exportDialog" width="680px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">导入用户数据</span>
      <div v-loading="loading" element-loading-text="数据解析中..." element-loading-background="rgba(0, 0, 0, 0.8)" class="dialoginfo" style="text-align: center;">
        <el-upload class="upload-demo" :on-success="fileSuccess" :before-upload="filebefore" :show-file-list="false" drag action="/base/system/user/importPersonalUserList" name="file" :headers="upheader">
          <i slot="trigger" class="el-icon-upload"></i>
          <div slot="trigger" class="el-upload__text">
            将文件拖到此处，或
            <em>点击选取文件</em>
          </div>
        </el-upload>
        <div style="padding-top: 10px;">
          <el-button class="bottom_all" style="margin-left: 0px;" @click="importSubmit()">下载模板</el-button>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="exportDialog = false">关 闭</el-button>
      </span>
    </el-dialog>
    <Organization :default="dialogForm.organizationId" :visible="organVisible" :dataSource="orangeoptions" :showArr="allOrganizationArr" title="选择组织" @handleSure="handleSure" @handleClose="organVisible=false" />
  </div>
</template>

<script>
import Organization from '@/components/organization';
import { getDicType } from "@/api/common";
import {
  queryPage,
  saveOrUpdate,
  updateOrDelete,
  queryjobPage,
  updateSortNum,
  reset_password, Download,
  exportTemplate2,
} from "@/api/basedata/user";
import { organization as organgequeryPage } from "@/api/basedata/PersonalRights.js";
import breaDcrumb from "@/components/breadcrumb";
import { mapGetters } from "vuex";
// import { formatOrganization } from "@/utils/utils";
import { sortReg } from "@/common/RegExp.js";
import { getUserInfo } from "@/utils/auth.js";
import {
  getToken,
  getUserId
} from '@/utils/auth';
export default {
  components: {
    breaDcrumb,
    Organization,
  },
  data() {
    var validatePass1 = (rule, value, callback) => {
      if (sortReg(value)) {
        callback();
      } else {
        callback(new Error("请输正整数序号!"));
      }
    };
    return {
      upheader: {},
      loading: false,
      exportDialog: false,
      userInfo: '',
      allorangeoptions: [],
      organVisible: false,
      dataSource: [],
      DownloadURL: Download,
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        organizationId: [
          { required: true, message: "请选择组织", trigger: "change" },
        ],
        phoneNum: [{ required: true, message: "请输入电话", trigger: "blur" }],
        loginAccount: [
          { required: true, message: "请输入登录账号", trigger: "blur" },
        ],
        loginType: [
          { required: true, message: "请选择登录方式", trigger: "change" },
        ],
        sortNum: [{ required: true, message: "请输入排序号", trigger: "blur" },
        { validator: validatePass1, trigger: "blur", }],
      },
      defaultProps: {
        children: "children",
        label: "name",
      },
      stationoptions: [],
      orangeoptions: [],
      /*添加修改弹窗*/
      dialogVisible: false,
      dialogtitle: "添加个人用户",
      /*判断收起展开*/
      showCardNav: true,
      /*列表展示*/
      tableColumns: [
        { label: "名称", width: "120", prop: "name", status: true },
        {
          label: "组织",
          width: "260",
          prop: "organizationShowInfo",
          status: true,
        },
        { label: "岗位", width: "120", prop: "stationName", status: true },
        { label: "电话", width: "120", prop: "phoneNum", status: true },
        {
          label: "登录账号",
          width: "120",
          prop: "loginAccount",
          status: true,
        },
        { label: "登录方式", width: "120", prop: "loginType", status: true },
        { label: "排序号", width: "120", prop: "sortNum", status: true },
        { label: "状态", width: "120", prop: "enable", status: true },
        { label: "操作", width: 120, prop: "", status: true },
      ],
      /*列表选中的数据集*/
      SelectionTableData: [],
      tableData: [],
      total: 0,
      dialogTable: [],
      page: 1,
      pageSize: 10,
      dialogForm: {
        userEentrance: "entrance_personal",
        organizationIdarr: '请选择组织',
        companyId: '',
        name: "",
        organizationId: "",
        phoneNum: "",
        stationId: "",
        loginAccount: "",
        loginType: [1, 2],
        sortNum: "",
        enable: 1,
      },
      form: {
        organizationId: "",
        name: "",
        userEentrance: "entrance_personal",
      },
      sortIds: [],
      /*职务*/
      positionoptions: [],
      /*职级*/
      rankoptions: [],
      /*用户类型*/
      usertypesoptions: [],
      ButtonList: [],
      allOrganizationArr: [],//选中的回显数据
      tableLoading: false,

      treeLoading: false
    };
  },
  created() {
    this.treeLoading = true;
    this.upheader = {
      'access-token': getToken(),
      'user-id': getUserId()
    }
    this.userInfo = getUserInfo()
    this.ButtonList = this.$ButtonList()
    queryjobPage({ page: 1, pageSize: 10000, enable: 1 }).then((res) => {
      this.stationoptions = res.data.data;
    });
    this.orangeoptions = [];
    organgequeryPage().then((res) => {
      if (res.code === 1001) {
        const { data } = res;
        let orangeoptionsList = data;
        this.diGui(orangeoptionsList);
        this.orangeoptions = orangeoptionsList;
        this.treeLoading = false
      }
    });
    getDicType({ code: "position" }).then((res) => {
      this.positionoptions = res.data.items;
    });
    getDicType({ code: "rank" }).then((res) => {
      this.rankoptions = res.data.items;
    });
    getDicType({ code: "usertypes" }).then((res) => {
      this.usertypesoptions = res.data.items;
    });
  },
  methods: {
    //递归判断是否是子节点,如果要改变数组长度就用反循环
    diGui(arr) {
      if (arr.length > 0) {
        for (let i = arr.length - 1; i >= 0; i--) {
          if (arr[i].children != null && arr[i].children.length > 0) {
            arr[i].children.forEach((v) => {
              v.City = arr[i].id
            })
            this.diGui(arr[i].children)
          }
        }
      }
    },
    /**查询父级 */
    handleSure(data) {
      this.organVisible = false;
      const allOrganization = this.getParent(this.orangeoptions, data[0].id);
      console.log(JSON.parse(JSON.stringify(allOrganization)))
      this.allOrganizationArr = allOrganization
      this.dialogForm.organizationId = data[0].id;
      this.dialogForm.organizationIdarr = allOrganization.map(item => item.name).join('-');
      this.organizationShowInfo = this.dialogForm.organizationIdarr
    },
    //子级查找父级对象
    getParent(data2, nodeId2) {
      var arrRes = [];
      let rev = (data, nodeId) => {
        for (var i = 0, length = data.length; i < length; i++) {
          let node = data[i];
          if (node.id == nodeId) {
            arrRes.unshift(node);
            //City父级id
            rev(data2, node.City);
            break;
          } else {
            if (node.children) {
              rev(node.children, nodeId);
            }
          }
        }
        return arrRes;
      };
      arrRes = rev(data2, nodeId2);
      return arrRes;
    },
    showVisible() {
      this.organVisible = true;
      if (this.allOrganizationArr.length > 0) {//选中的回显自定义颜色
        this.allOrganizationArr = this.allOrganizationArr.map(res => (res.id))
        console.log(this.allOrganizationArr);
      }
    },
    setTree(e) {
      this.form.organizationId = e.id;
      this.initData();
    },
    /*更新排序号*/
    updateSortNum() {
      const sorts = []
      this.tableData.forEach((v) => {
        sorts.push({ id: v.id, sortNum: v.sortNum });
      })
      updateSortNum(sorts).then((res) => {
        if (res.code === 1001) {
          this.$message.success('更新成功');
          this.initData();
        }
      });
    },
    initData() {
      let params = {
        ...this.form,
        page: this.page,
        pageSize: this.pageSize,
      };
      this.tableLoading = true;
      queryPage(params).then((res) => {
        this.tableLoading = false;
        this.tableData = res.data.data;
        this.total = res.data.totalRows
      });
    },
    resetData() {
      this.page = 1
      this.$refs.form.resetFields();
      this.initData();
    },
    resefrom() {
      this.dialogVisible = false;
    },
    add() {
      this.dialogVisible = true;
      this.$data.dialogForm = this.$options.data().dialogForm;
      setTimeout(() => {
        this.$refs.dialogForm.clearValidate();
      }, 10);
      this.dialogtitle = "添加个人用户";
    },
    updateType(index) {
      const self = this;
      this.$confirm(
        `确定${index === 1 ? "启用" : index === 2 ? "禁用" : "删除"
        }选中的数据?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          cancelButtonClass: "bottom_all_two",
          confirmButtonClass: "bottom_all",
          type: "warning",
        }
      )
        .then(() => {
          switch (index) {
            case 1: {
              let params = {
                status: 1,
                type: "update_enable",
              };
              self.handleData(params);
              return;
            }
            case 2: {
              let params = {
                status: 0,
                type: "update_enable",
              };
              self.handleData(params);
              return;
            }
            case 3: {
              let params = {
                status: 0,
                type: "update_status",
              };
              self.handleData(params);
              return;
            }
            default:
              break;
          }
        })
        .catch(() => { });
    },
    handleData(data) {
      const params = {
        ...data,
        ids: this.SelectionTableData,
      };
      updateOrDelete(params).then(() => {
        this.initData();
        this.$message({
          message: "操作成功！",
          type: "success",
        });
      });
    },
    resetPassword() {
      if (this.SelectionTableData.length == 0) {
        this.$message({
          message: "请先选择用户！！！",
          type: "warning",
        });
        return
      }
      reset_password(this.SelectionTableData).then(res => {
        if (res.code == 1001) {
          this.$message({
            message: "密码重置成功",
            type: "success",
          });
        }

      })
    },
    update(data) {
      /**
       * @Description: 修改岗位
       * @Param:
       * @Author: wangwangwang
       */
      this.dialogVisible = true;
      this.dialogtitle = "修改个人用户";
      this.dialogForm = data;
      this.dialogForm.loginType = data.loginType === 3 ? [1, 2] : [data.loginType]
      this.dialogForm.organizationIdarr = data.organizationShowInfo;
      setTimeout(async () => {
        this.$refs.dialogForm.clearValidate();
        await this.handleSure([{ id: data.organizationId }])
      }, 10);
    },
    handleSelectionChange(val) {
      const data = [];
      this.sortIds = [];
      for (let i in val) {
        data.push(val[i].id);
        this.sortIds.push({ id: val[i].id, sortNum: val[i].sortNum });
      }
      this.SelectionTableData = data;
    },
    sureSubmit() {
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          const params = {
            ...this.dialogForm,
            loginType: this.dialogForm.loginType.length === 2 ? 3 : this.dialogForm.loginType[0],
          };
          saveOrUpdate(params).then((res) => {
            if (res.code === 1001) {
              this.$message({
                message: "操作成功！",
                type: "success",
              });
              this.resefrom();
              this.initData();
              this.dialogVisible = false;
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleCheckChange(e) {
      this.mineStatusValue = e.label;
      this.mineStatus = e.label;
    },
    fileSuccess(res) {
      this.loading = false
      if (res.code == 1001) {
        this.$message({
          dangerouslyUseHTMLString: true,
          message: `本次导入数据成功${res.data.successNum}条，失败<span style="color:red">${res.data.failureNum}</span>条！！！`,
          type: 'success'
        });
        if (res.data.failureNum !== 0) {
          let text = res.data.errResult.map(res => (`第${res.sortNum}行` + res.reason)).join(';');
          this.$notify.error({
            title: '导入失败用户',
            message: text,
            duration: 0
          });
        }
        if (res.data.successNum !== 0) {
          this.initData()
        }
      } else {
        this.$message.error(res.codeMsg);
      }
    },
    filebefore(file) {
      this.loading = true
      const isJPG = file.type === 'application/vnd.ms-excel';
      if (!isJPG) {
        this.$message.error('数据上传必须是 xls 格式!');
        this.loading = false
      }
      return isJPG;
    },
    /**下载模板*/
    importSubmit() {
      this.$Download(exportTemplate2)
    },
    sizeChange(value) {
      this.pageSize = value;
      this.initData();
    },
  },
  mounted() {
    this.initData();
  },
  computed: {
    ...mapGetters({
      screenWidth: "getscreenWidth",
      screenHeight: "getscreenHeight",
      Collapse: "getsCollapse",
    }),
    style() {
      let num = 0;
      if (this.Collapse) {
        num = this.screenWidth - 324;
      } else {
        num = this.screenWidth - 420;
      }
      return "width:" + num + "px;";
    },
  },
};
</script>
<style>
.is-current > .el-tree-node__content {
  color: var(--bg_color);
}
</style>
<style lang="scss" scoped>
.el-tree {
  display: inline-block;
}
.el-input,
.el-cascader,
.el-select {
  width: 220px;
}
.CodingRules {
  .el-link {
    i {
      font-size: 14px;
      color: $bg_color;
    }
  }
  .el-link:hover {
    color: $bg_color;
  }
  font-size: $font_size;
}
</style>
